package com.zhf.web.servlet;

import com.zhf.base.Constants;
import com.zhf.pojo.Course;
import com.zhf.service.CourseService;
import com.zhf.service.impl.CourseServiceImpl;
import com.zhf.utils.DateUtils;
import com.zhf.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: ZhaoHuanfeng
 * @Date: 2020/10/30 22:19
 */
@WebServlet(name = "CourseSalesInfoServlet", urlPatterns = "/CourseSalesInfo")
public class CourseSalesInfoServlet extends HttpServlet {

    /**
     * 保存课程营销信息
     * 收集表单数据，封装到course中，将图片上传到Tomcat服务器
     *
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            //创建course对象
            Course course = new Course();
            //创建Map集合，用来收集数据
            Map<String, Object> map = new HashMap<>();
            //创建磁盘工厂对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //文件上传核心对象
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //解析request对象，获取表单项集合
            List<FileItem> list = fileUpload.parseRequest(request);
            //遍历集合，判断哪些是普通的表单项哪些是文件表单项
            for (FileItem item :
                    list) {
                boolean formField = item.isFormField();
                if (formField) {
                    //普通表单项中的数据并保存到map中
                    String fieldName = item.getFieldName();
                    String value = item.getString("utf-8");
                    System.out.println(fieldName + ":" + value);
                    map.put(fieldName, value);
                } else {
                    //文件上传项
                    //获取文件名
                    String fileName = item.getName();
                    String uuid = UUIDUtils.getUUID();
                    String newFileName = uuid + "_" + fileName;
                    //获取输入流
                    InputStream inputStream = item.getInputStream();
                    //获取webapps的目录路径
                    String realPath = this.getServletContext().getRealPath("/");
                    String webappsPath = realPath.substring(0, realPath.indexOf("lagou_edu_home"));
                    //创建输出流
                    FileOutputStream fileOutputStream = new FileOutputStream(webappsPath + "/upload/" + newFileName);
                    IOUtils.copy(inputStream, fileOutputStream);
                    //关闭流
                    fileOutputStream.close();
                    inputStream.close();
                    //将图片路径进行保存
                    map.put("course_img_url", Constants.LOCAL_URL + "/upload/" + newFileName);
                }
            }

            //使用BeanUtils将map中的数据封装到course对象
            BeanUtils.populate(course, map);
            //获取时间
            String dateFormart = DateUtils.getDateFormart();

            CourseService courseService = new CourseServiceImpl();

            if (map.get("id") != null) {
                //修改操作
                //补全信息
                //修改时间
                course.setUpdate_time(dateFormart);

                //业务处理
                String result = courseService.updateCourseInfo(course);
                //响应请求
                response.getWriter().print(result);
            } else {
                //新建操作
                //补全信息
                //创建时间
                course.setCreate_time(dateFormart);
                //修改时间
                course.setUpdate_time(dateFormart);
                //上架
                course.setStatus(1);

                //业务处理
                String result = courseService.saveCourseSalesInfo(course);

                //响应请求
                response.getWriter().print(result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
